<template>
  <!-- 动态字段表单 -->
  <el-form
    label-width="1.6rem"
    class="dynamicForm"
    :disabled="formdata.isReadonly==1||formdata.type=='query'"
    >
    <!-- 动态字段 -->
    <el-form-item v-for="(row,index) in formdata.siteModelFileds" :class="row.isRequired=='1'?'is-required':''"
     :key="index" :label="row.filedNameLable" :prop="row.filedName">
      <el-row v-if="row.filedClass=='input'||row.filedClass=='link'">
        <el-input 
        :style="'width:'+(row.sizeRatio*100)+'%;'"
        clearable :maxlength="100"
        v-model="formdata.editeModelContent[row.filedName]"></el-input>
        {{row.unit}}
      </el-row>
      <el-row v-else-if="row.filedClass=='inputGroup'">
        <el-input :style="'width:'+(row.sizeRatio*100)+'%;'" clearable :maxlength="100" v-model="row.inputGroup1"
         @change="val=>{formdata.editeModelContent[row.filedName]=(row.inputGroup1||'')+'|'+(row.inputGroup2||'')}"></el-input>
        -
        <el-input :style="'width:'+(row.sizeRatio*100)+'%;'" clearable :maxlength="100" v-model="row.inputGroup2"
         @change="val=>{formdata.editeModelContent[row.filedName]=(row.inputGroup1||'')+'|'+(row.inputGroup2||'')}"></el-input>
        {{row.unit}}
      </el-row>
      <el-input
       v-else-if="row.filedClass=='textarea'" :rows="4"
       type="textarea" 
       v-model="formdata.editeModelContent[row.filedName]"
       :maxlength="500"></el-input>
      <div class="box-images" v-else-if="row.filedClass=='images'" >
        <span class="toptxt" v-if="row.filedCheckTips">{{row.filedCheckTips}}</span>
        <el-upload
          
          :action="uploadUrl"
          list-type="picture-card"
          :file-list="multiImageUploadList[row.filedName]"
          :data="{'filedName':row.filedName}"
          :http-request="uploadImages"
          :on-change="imagesControlChange"
          :on-remove="imagesControlRemove"
          :before-upload="beforeImageUpload"
          :limit="12"
          >
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
      <div v-else-if="row.filedClass=='image'" class="box-image">
        <span class="toptxt" v-if="row.filedCheckTips">{{row.filedCheckTips}}</span>
        <el-upload
          
          class="avatar-uploader"
          :action="uploadUrl"
          :show-file-list="false"
          :on-success="imageControl_handleSuccess"
          :data="{'filedName':row.filedName}"
          :http-request="uploadImage"
          :before-upload="beforeImageUpload">
          <img v-if="singleImageUploadUrl[row.filedName]" :src="singleImageUploadUrl[row.filedName]" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <div v-else-if="row.filedClass=='tag'" class="box-label">
        <span class="toptxt">请选中符合的标签或添加自定义标签</span>
        <el-tag
          
           v-for="(tag,indextag) in row.filedReferencesArray"
          :key="indextag"
          closable
          :disable-transitions="false"
          @close="tagsInfo_handleClose(tag,row)">
          {{tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="row.tagInputVisible"
          v-model="row.tagInputValue"
          :ref="row.tagInputRef"
          size="small"
          @keyup.enter.native="tagsInfo_handleInputConfirm(row)"
          @blur="tagsInfo_handleInputConfirm(row)"
        >
        </el-input>
        <el-button  v-else class="button-new-tag" size="small" @click="tagsInfo_showInput(row)">+ 标签</el-button>
      </div>
      <div v-else-if="row.filedClass=='editor'">
         <!-- <keep-alive>
            <editor ref="richtxtEditor" 
                :id="row.editorId" 
                v-bind:r_content="formdata.editeModelContent[row.filedName]"
                :hight="500">
            </editor>
          </keep-alive> -->
          <wangeditor
            :contenteditable="formdata.type!='query'&&formdata.isReadonly!=1"
            :editorId="'dynamicFormEditor'+index"
            :catchData="(d)=>{formdata.editeModelContent[row.filedName]=d;}"
            :content="formdata.editeModelContent[row.filedName]"></wangeditor>
      </div>
      <div v-else-if="row.filedClass=='radio'">
        <template>
          <el-radio  v-for="(radio,rindex) in row.filedReferencesArray" :key="rindex" v-model="formdata.editeModelContent[row.filedName]" :label="rindex">{{radio}}</el-radio>
        </template>
      </div>
      <div v-else-if="row.filedClass=='dateInput'">
        <el-date-picker
          
          v-model="formdata.editeModelContent[row.filedName]"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择日期">
        </el-date-picker>
      </div>
      <div v-else-if="row.filedClass=='checkbox'">
        <el-checkbox-group v-model="formdata.editeModelContent[row.filedName]">
          <el-checkbox  v-for="(radio,rindex) in row.filedReferencesArray" :key="rindex" :label="radio"></el-checkbox>
        </el-checkbox-group>
      </div>
      <!-- <div v-else-if="row.filedClass=='link'">
        
      </div> -->
      <div v-else-if="row.filedClass=='select'">
        <el-select  v-model="formdata.editeModelContent[row.filedName]" placeholder="请选择">
          <el-option
            v-for="(item,rindex) in row.filedReferencesArray"
            :key="rindex"
            :label="item"
            :value="item">
          </el-option>
        </el-select>
      </div>
    </el-form-item>

  </el-form>

</template>

<script>
// import editor from '@/components/common/editor'
import wangeditor from './wangeditor'
export default {
  components:{wangeditor},
  props:['dynamicForm'],
  data() {
    return {
      formdata:this.dynamicForm,
      /**单张图片url属性
       * 需根据传入数据初始化属性
       */
      singleImageUploadUrl:{},
      /**多张图片url属性
       * 需根据传入数据初始化属性
       */
      multiImageUploadList:{},
      uploadUrl: window.config.baseUrl + "/file/upload",
    };
  },
  methods: {
    init(){
      // console.log(this.formdata)
      this.formateData(this.formdata.siteModelFileds,this.formdata.editeModelContent);
      //新增类型重置所有数据
      if(this.formdata.type=='add'){
        this.resetData(this.formdata.editeModelContent);
        this.resetData(this.singleImageUploadUrl);
        this.resetData(this.multiImageUploadList);
      }
    },
    /**格式化数据 */
    formateData(data,valueData){
      for(let i=0;i<data.length;i++){
        let row=data[i];
        if(row.filedClass=='image'){
          this.$set(this.singleImageUploadUrl,row.filedName,valueData[row.filedName]);
        }
        else if(row.filedClass=='images'){
          valueData[row.filedName]=valueData[row.filedName]==''?[]:valueData[row.filedName];
          let urlsobj=valueData[row.filedName].map(d=>{
            return {
              url:d,
              name:row.filedName
            }
          })
          this.$set(this.multiImageUploadList,row.filedName,urlsobj);
        }
        else if(row.filedClass=='inputGroup'){
          this.$set(row,'inputGroup1','');
          this.$set(row,'inputGroup2','');
          if(valueData[row.filedName]){
            let val=valueData[row.filedName].split('|');
            row.inputGroup1=val[0];
            row.inputGroup2=val[1];
          }
          
        }
      }
    },
    /**重置数据 */
    resetData(data){
      for(let key in data){
        if(typeof(data[key])=='string'||typeof(data[key])=='number'){
          data[key]='';
        }
        else if(typeof(data[key])=='object'&&Array.isArray(data[key])){
          data[key]=[];
        }
        else{
          data[key]=null;
        }
      }
    },
    // campusChange : function(campusId) { //校区改变
    //   this.init();
    // },
    imageControl_handleSuccess(res, file) {
      // console.log(file)
      // this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeImageUpload(file) {
      // console.log(file.type)
      const isJPG = (file.type === 'image/jpeg'||file.type === 'image/gif'||file.type === 'image/png'||file.type === 'image/bmp');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('图片格式不支持'+file.type);
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB');
      }
      return isJPG && isLt2M;
    },
    /**
     * 自定义上传图片*单张图片
     */
    uploadImage(d){
      // console.log(d)
      let self=this;
      let file=d.file;
      let filedName=d.data.filedName;
      let filedata = new FormData(); //创建form对象
      filedata.append('file',file,file.name);//通过append向form对象添加数据
      filedata.append('content','officialWebsite');//添加form表单中其他数据
      api.uploadFile(filedata).then(function(d){
        if(d.result="操作成功"){		          	   		
          self.singleImageUploadUrl[filedName] = d.url;
        }
      });
      
    },
    /**
     * 自定义上传图片*多张图片
     */
    uploadImages(d){
      // console.log(d)
      let self=this;
      let file=d.file;
      let filedName=d.data.filedName;
      let filedata = new FormData(); //创建form对象
      filedata.append('file',file,file.name);//通过append向form对象添加数据
      filedata.append('content','officialWebsite');//添加form表单中其他数据
      api.uploadFile(filedata).then(function(d){
        if(d.result="操作成功"){
          self.multiImageUploadList[filedName].push({
            url:d.url,
            name:filedName
          });
        }
      });
      
    },
    imagesControlChange(file, fileList){
      // console.log(file)
      // console.log(this.multiImageUploadList)
    },
    imagesControlRemove(file, fileList){
     
      let filedName=file.name;
      let index=-1;
      if(this.multiImageUploadList[filedName]){
        this.multiImageUploadList[filedName].forEach((row,i)=>{
        if(row.uid==file.uid)
          {
            index=i;
          }
        });
        this.multiImageUploadList[filedName].splice(index,1);
      }
      
    },
    tagsInfo_handleClose(tag,data) {
      // console.log(tag)
      data.filedReferencesArray.splice(data.filedReferencesArray.indexOf(tag), 1);
    },
    tagsInfo_showInput(row) {
      // row.tagInputVisible = true;
      // this.$nextTick(_ => {
      //   this.$refs[row.tagInputRef][0].$refs.input.focus();
      // });
      
      row.tagInputVisible=true;
      this.$nextTick(_ => {
        this.$refs[row.tagInputRef][0].$refs.input.focus();
      });
    },
    tagsInfo_handleInputConfirm(row) {
      // console.log(row)
      if(row.tagInputValue==''){
        row.tagInputVisible=false;
        return;
      }
      if(row.tagInputValue.length>20){
        this.$message({
          message: '添加失败，单个标签最多支持20个字符！',
          type: 'warning'
        });
        row.tagInputValue = '';
        row.tagInputVisible=false;
        return;
      }
      if(row.tagInputValue.includes('|')){
        this.$message({
          message: '不支持 | 字符串，请重新输入！',
          type: 'error'
        });
        row.tagInputValue='';
        row.tagInputVisible=false;
        return;
      }
      if(row.filedReferencesArray.includes(row.tagInputValue)){
        this.$message({
          message: '标签内容不可重复！',
          type: 'warning'
        });
        row.tagInputVisible=false;
        row.tagInputValue = '';
        return;
      }
      if(row.filedReferencesArray.length>=50){
        this.$message({
          message: '最多支持50个标签！',
          type: 'warning'
        });
        row.tagInputVisible=false;
        row.tagInputValue = '';
        return;
      }
      row.filedReferencesArray.push(row.tagInputValue);
      row.tagInputVisible=false;
      row.tagInputValue = '';
    }
  },
  mounted() {
	  this.init();
  },
  computed: {},
  watch: {},
  // created: function() {
  //   this.formateData(this.formdata.siteModelFileds);
  // }
};
</script>

<style lang="scss">
.dynamicForm {
  .box-label{
      .toptxt{
        width: 100%;
        color: #666666;
        font-style: italic;
        display: inline-block;
      }
      .el-tag  {
        margin-left: 0.1rem;
      }
      .button-new-tag {
        margin-left: 0.1rem;
        height: 0.32rem;
        line-height: 0.3rem;
        padding-top: 0;
        padding-bottom: 0;
      }
      .input-new-tag {
        width: 0.9rem;
        margin-left: 0.1rem;
        vertical-align: bottom;
      }
  }
  .box-image{
    .toptxt{
      width: 100%;
      color: #666666;
      font-style: italic;
      display: inline-block;
    }
    .avatar-uploader .el-upload {
      border: 0.01rem dashed #d9d9d9;
      border-radius: 0.06rem;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: #409EFF;
    }
    .avatar-uploader-icon {
      font-size: 0.28rem;
      color: #8c939d;
      width: 1.78rem;
      height: 1.78rem;
      line-height: 1.78rem;
      text-align: center;
    }
    .avatar {
      width: 1.78rem;
      height: 1.78rem;
      display: block;
    }
  }
  .box-images{
    .toptxt{
      width: 100%;
      color: #666666;
      font-style: italic;
      display: inline-block;
    }
    .el-upload-list__item:not(.is-success){
      display: none !important;
    }
  }
  .el-form-item__label{
    font-size: 0.16rem !important;
  }
  .el-form-item__content{
    padding-right: 1rem;
    font-size: 0.16rem !important;
    .el-input{
      font-size: 0.16rem !important;
    }
    .el-textarea{
      font-size: 0.16rem !important;
    }
  }
}
</style>